#Requires AutoHotkey v2.0

; 读取 CSV 文件函数
readCSV(filePath) {
    csvContent := []
    FileRead(csvContent, filePath)
    
    ; 使用 `StrSplit` 按行分割 CSV 内容
    rows := StrSplit(csvContent, "`n")
    
    ; 解析每一行
    for row in rows {
        fields := []
        ; 使用正则表达式匹配字段，考虑逗号和双引号
        while (pos := RegExMatch(row, "(\"[^\"]*(?:\"\"[^\"]*)*\"|[^,]*)", match, pos+1)) {
            ; 去掉外部双引号并处理内部双引号
            field := match1
            if (SubStr(field, 1, 1) = """") {
                field := StrReplace(SubStr(field, 2, -1), "\"\"", """")
            }
            fields.Push(field)
        }
        ; 存储解析后的字段
        csvContent.Push(fields)
    }
    return csvContent
}

; 写入 CSV 文件函数
writeCSV(filePath, csvContent) {
    file := FileOpen(filePath, "w")
    for fields in csvContent {
        line := ""
        for field in fields {
            ; 如果字段包含逗号或双引号，则用双引号括起来并处理内部双引号
            if (InStr(field, ",") || InStr(field, """")) {
                field := """" StrReplace(field, """", "\"""") """"
            }
            line .= (line != "" ? "," : "") field
        }
        file.Write(line "`n")
    }
    file.Close()
}

; 示例用法
csvContent := readCSV("D:\window\desktop\工作簿1.csv")
MsgBox "CSV 内容读取完毕。"

; 修改 CSV 内容并写入新文件
csvContent[1].Push("New Value")
writeCSV("example_modified.csv", csvContent)
MsgBox "CSV 内容写入完毕。"
